import hashlib
from contextlib import contextmanager
from colorama import Fore, Back, Style
import hashlib, binascii


# 1.
def func1():
    pk = hashlib.pbkdf2_hmac('sha512', b'key', b'hello python', 9999, dklen=32)  # 高级算法
    conn = binascii.hexlify(pk)
    print(conn)


func1()


# 2.
def func2():
    with open('test.py', 'w+', encoding='utf-8') as file:
        file.write('hello python')

    with open('test.py', 'r+', encoding='utf-8') as file:
        content = file.read()
        md5 = hashlib.md5()
        md5.update(content.encode('utf-8'))
        print(md5.hexdigest())


func2()

# 3.1
class MyClass():
    def __init__(self, a_str):
        print('初始化数据')
        self.a_str = a_str

    def __enter__(self):
        print('开始操作数据')
        self.a_str += 'hello'
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.a_str = None
        if exc_type:
            print(exc_val)
        else:
            print('正常退出')

    def work(self):
        print('输出数据：%s' % self.a_str)


def func3_1():
    with MyClass('abc') as obj:
        obj.work()


# func3_1()


# 3.2
class MyClass2():
    def __init__(self, a_str):
        print('初始化数据')
        self.a_str = a_str

    def work(self):
        print('输出数据:%s' % self.a_str)


@contextmanager
def mk_work():
    print('开始处理数据')
    obj = MyClass2('hello')
    try:
        yield obj
    except Exception as e:
        print(e)

    print('数据处理完毕')


def func3_2():
    with mk_work() as mk:
        mk.work()


# func3_2()


# 4.
def func4():
    print(Fore.LIGHTBLACK_EX + 'hello')
    print(Back.GREEN + 'python')


func4()
